<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<template>
  <div class="pagination">
    <button style="margin-left: 30px" v-if="!total">没有数据了</button>
    <button v-show="pageNo==1?false:true" @click="$emit('getPageNo',pageNo-1)">上一页</button>
    <button v-show="startNumAndEndNum.start > 1" @click="$emit('getPageNo', 1)"
      :class="{active:pageNo==1}">1</button>
    <button v-show="startNumAndEndNum.start > 2">···</button>
    <button v-show="total&&page >= startNumAndEndNum.start"
      v-for="(page, idx) in startNumAndEndNum.end" :key="idx" @click="$emit('getPageNo', page)"
      :class="{active:pageNo==page}">{{ page
    }}</button>
    <button v-show="startNumAndEndNum.end < totalPage - 1">···</button>
    <button @click="$emit('getPageNo', totalPage)" v-show="startNumAndEndNum.end < totalPage"
      :class="{active:pageNo==totalPage}">{{ totalPage }}</button>
    <button v-show="pageNo==totalPage?false:true" v-if="total"
      @click="$emit('getPageNo',pageNo+1)">下一页</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  methods: {
  },
  // 分页器封装原理
  // 知道当前第几页pageNo
  // 知道分页器一共需要展示多少条数据total
  // 知道每一页需要展示数据的个数limit
  // 知道连续的页码数5|7  totalPage() { return Math.ceil(this.total / this.limit) },
  props: ['pageNo', 'limit', 'total', 'continues'],
  computed: {
    totalPage () {
      return Math.ceil(this.total / this.limit)
    },
    // 计算连续页码
    startNumAndEndNum () {
      const { continues, pageNo, totalPage } = this
      let start = 0; let end = 0
      // 如果数据比较少或者其他情况进行判断
      if (continues > totalPage) {
        start = 1
        end = totalPage
      } else {
        start = pageNo - parseInt(continues / 2)
        end = pageNo + parseInt(continues / 2)
        if (start < 1) {
          start = 1
          end = continues
        }
        if (end > totalPage) {
          start = totalPage - continues + 1
          end = totalPage
        }
      }
      return { start, end }
    }

  }
}
</script>

<style lang="less" >
.pagination {
  text-align: center;
  margin-bottom: 15px;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #101d37;
      color: #fff;
    }
  }
}
</style>
